import json
import random
import time
from urllib import request
from bs4 import BeautifulSoup

import mysql.connector
from fdfs_client.client import get_tracker_conf, Fdfs_client

def initMysql():
  global mydb
  global mycursor
  # mydb = mysql.connector.connect(
  #   host='8.129.219.66',
  #   user='guifangtong',
  #   passwd='guifangtong1234!@#',
  #   database='guifangtong'
  # )

  mydb = mysql.connector.connect(
    host='localhost',
    user='root',
    passwd='root1234',
    database='guifangtong'
  )
  mycursor = mydb.cursor()


def uploadPic(picurl):
  try:
    tracker_path = get_tracker_conf('./client.conf')
    client = Fdfs_client(tracker_path)
    # ret_upload
    # ret_upload = client.upload_by_filename('D://12.jpg') # 图片地址
    resp = request.urlopen(picurl)
    # image = np.asarray(bytearray(resp.read()), dtype="uint8")
    ret_upload = client.upload_by_buffer(resp.read())  # 图片地址
    # print(ret_upload['Remote file_id'])
    # print(ret_upload)
    return ret_upload['Remote file_id']
  except Exception as e:
    print('连接失败', e)


builds = ['南宁市龙光玖骏房地产开发有限公司', '南宁市耀辉房地产开发有限公司', '南宁市汉军房地产开发有限责任公司', '南宁市盈顺科技有限公司']
esteComs = ['龙光物业', '广东龙光集团物业管理有限公司南宁分公司', '深圳市深华物业集团有限公司南宁第一分公司', '世邦魏理仕']

def checkRMB(str):
    msg = str
    if str == '一':
      msg = 1
    elif str == '二' or str == '两':
      msg = 2
    elif str == '三':
      msg = 3
    elif str == '四':
      msg = 4
    elif str == '五':
      msg = 5
    elif str == '六':
      msg = 6
    elif str == '七':
      msg = 7
    elif str == '八':
      msg = 8
    elif str == '九':
      msg = 9
    elif str == '十':
      msg = 10
    return msg


def sousuoLgbHx(fangId,fang_hengbao_id):
  initMysql()
  # url = 'https://lgbao.logan.com.cn/olshow/v1/web/product/estate/query/recommend?city=450100&province=450000&recommendData=1'
  # url = 'https://hfb.hengfangbao.cn/api/public/houses?page='+str(page_index)+'&pageSize=100'
  url = 'https://hfb.hengfangbao.cn/api/public/biz_item?item_id='+fang_hengbao_id
  # 直接请求
  response = request.urlopen(url)
  # 获取状态码，如果是200表示成功
  # print(response.status)
  # 读取网页内容
  context = response.read().decode('utf-8')
  data = json.loads(context)
  layout_obj = data['result']
  table_namet = "t_layout"
  # print('layout_img_info',layout_obj['layout_img_info'])
  for item in layout_obj['layout_img_info']:
    creat_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    layout_title = item['layout_title']
    if layout_title[0:1] != '昌':
      if '厅' in layout_title:
        if layout_title[1:2] == '房':
          shi = checkRMB(layout_title[0:1])
          ting = checkRMB(layout_title[2:3])
          # print(',,,',layout_title[4:5])
          if layout_title[4:5] != '卫' and layout_title[4:5] != '':
            wei = checkRMB(layout_title[4:5])
            kkk = random.randint(0, 2)
            pic = item['layout_img'][0]
            # picurl = pic
            picurl = uploadPic(pic)
            picurl = picurl.decode('utf-8')
            area = item['layout_area']
            sale_status = item['sale_status']
            if sale_status == 0:
               sale_status = 2
            area_str = str(area) +'㎡'
            price = 30000 * (kkk+1)
            print("桂房通fang_id:"+str(fangId)+"-->恒房宝fang_hengbao_id:"+str(fang_hengbao_id)+'-->正在添加户型。。。',str(shi)+'房'+str(ting)+'厅'+str(wei)+'卫')
            sql = "INSERT INTO " + table_namet + " (create_time,deleted,area,name,shi,ting,wei,pic,price,fang_id,square,status,commission) VALUES (%s,%s,%s,%s,%s, %s, %s, %s,%s, %s, %s, %s,%s)"
            val = (creat_time,0,area_str,layout_obj['name'],checkRMB(shi),checkRMB(ting),checkRMB(wei),picurl,str(price),str(fangId),str(area),sale_status,str((kkk+1)*price))
            # print(sql,val)
            mycursor.execute(sql, val)
            mydb.commit()

def findFangs():
  initMysql()
  table_name = 't_fang'
  sql = "select * from " + table_name
  mycursor.execute(sql)
  myresult = mycursor.fetchall()  # fetchall() 获取所有记录
  return myresult

if __name__ == '__main__':
  # sousuoLgbHx()
  # strr = '3房5厅2卫'

  # strr = '四房两厅两卫'
  # shi = strr[0:1]
  # d = checkRMB(shi)
  # print(d)

  # sousuoLgbHx('5','217')

  resFangs = findFangs()
  for item in resFangs:
    fang_id = item[0]
    fang_hengbao_id = item[12]
    sousuoLgbHx(fang_id,fang_hengbao_id)
    time.sleep(1)

  # print(strr[0:1])
  # print(strr[2:3])
  # print(strr[4:5])
